#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.prod'

import django
django.setup()


from django.db.models import Q
import json, requests, hashlib, datetime, os, base64, hmac, time
from django_redis import get_redis_connection
from bs4 import BeautifulSoup
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import algorithms
from gmssl import sm3, func

from users.models import Level, User
from random import Random
from vouchers.models import AliDiscountCouponInfo
from activities.models import Channel
from equity_mall.utils.wash_level1 import get_result, post_result


def get_level_list(level):
    '''根据当前用户，获取层级下用户列表'''
    redis_conn = get_redis_connection("lower_level")
    level_list_server = redis_conn.get(f'level_{level.id}')
    if level_list_server:
        return json.loads(level_list_server.decode())
    level_list = list(Level.objects.filter(Q(id=level.id) |
                                           Q(parent_id=level.id) |
                                           Q(parent__parent_id=level.id) |
                                           Q(parent__parent__parent_id=level.id) |
                                           Q(parent__parent__parent__parent_id=level.id)).values_list('id', flat=True))
    redis_conn.set(f'level_{level.id}', json.dumps(level_list))
    return level_list


def random_str(randomlength=32):
    strs = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        strs += chars[random.randint(0, length)]
    return strs


def redis_baidu_token():
    # client_id 为官网获取的AK， client_secret 为官网获取的SK
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=Semj9DaYGyC4OkSLOacPzsQ3&client_secret=vRq4dUNt58NUUyonPheTL5HlxyCX8Qt3'
    response = requests.get(host)
    data = response.json()
    if response:
        redis_conn = get_redis_connection("baidu")
        redis_conn.setex('access_token', data['expires_in'], data['access_token'])
        return data['access_token']


def redis_scheme_token():
    host = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx47154e2c003035e6&secret=457ce6d7ee67218b17cee32757842431'
    response = requests.get(host)
    data = response.json()
    if response:
        redis_conn = get_redis_connection("scheme")
        redis_conn.setex('access_token', data['expires_in'], data['access_token'])
        return data['access_token']


def redis_scheme_token_equity():
    host = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxf68630951d36fd07&secret=8622bd908f8e5aa721dc9287d08e548f'
    response = requests.get(host)
    data = response.json()
    if response:
        redis_conn = get_redis_connection("scheme")
        redis_conn.setex('access_token_equity', data['expires_in'], data['access_token'])
        return data['access_token']


def redis_scheme_token_wyh():
    host = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx950122ad80dc97c9&secret=a2cdeb77110b42a69a27a68c1d526d81'
    response = requests.get(host)
    data = response.json()
    if response:
        redis_conn = get_redis_connection("scheme")
        redis_conn.setex('wyh_access_token', data['expires_in'], data['access_token'])
        return data['access_token']


def chack_identify(idNumber):
    '''校验身份证真伪'''
    url = 'https://qifu.baidu.com/api/sme/aladdin/idquery'
    timestamp = (datetime.datetime.now() + datetime.timedelta(hours=-8)).strftime('%Y-%m-%dT%H:%M:%SZ')
    params_str = f'POST/idquery{timestamp}ieq%$jsaf23!@fkjwie'
    md5 = hashlib.md5()  # 使用MD5加密模式
    md5.update(params_str.encode('utf-8'))  # 将参数字符串传入
    sign = md5.hexdigest()
    headers = {"timestamp": f"{timestamp}@{sign}", "Content-Type": "application/json"}
    body = {"idNumber": idNumber}
    try:
        response = requests.post(url=url, headers=headers, data=json.dumps(body))
        return response.json()
    except:
        return {'error': '身份证校验失败, 请联系管理员'}


def get_sign(data_dict, key):
    """
    签名函数
    :param data_dict: 需要签名的参数，格式为字典
    :param key: 密钥 ，即上面的API_KEY
    :return: 字符串
    """
    params_list = sorted(data_dict.items(), key=lambda e: e[0], reverse=False)  # 参数字典倒排序为列表
    params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list) + '&key=' + key
    # 组织参数字符串并在末尾添加商户交易密钥
    md5 = hashlib.md5()  # 使用MD5加密模式
    md5.update(params_str.encode('utf-8'))  # 将参数字符串传入
    sign = md5.hexdigest().upper()  # 完成加密并转为大写
    return sign


def get_postallive_MD5_sign(data_dict, key):
    params_list = sorted(data_dict.items(), key=lambda e: e[0], reverse=False)
    params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list) + '&secret=' + key
    md5 = hashlib.md5()
    md5.update(params_str.encode('utf-8'))
    sign = md5.hexdigest().upper()
    return sign


def trans_dict_to_xml(data_dict):
    """
    定义字典转XML的函数
    :param data_dict:
    :return:
    """
    data_xml = []
    for k in sorted(data_dict.keys()):  # 遍历字典排序后的key
        v = data_dict.get(k)  # 取出字典中key对应的value
        if k == 'detail' and not v.startswith('<![CDATA['):  # 添加XML标记
            v = '<![CDATA[{}]]>'.format(v)
        data_xml.append('<{key}>{value}</{key}>'.format(key=k, value=v))
    return '<xml>{}</xml>'.format(''.join(data_xml))  # 返回XML


def trans_xml_to_dict(data_xml):
    """
    定义XML转字典的函数
    :param data_xml:
    :return:
    """
    soup = BeautifulSoup(data_xml, features='xml')
    xml = soup.find('xml')  # 解析XML
    if not xml:
        return {}
    data_dict = dict([(item.name, item.text) for item in xml.find_all()])
    return data_dict


def bind_customer(unionid):
    url = 'https://api.gdwxyf.com/api/userBindApp.do'
    data = {
        "program_id": "201519556510031029",
        "unionid": unionid
    }
    key = '5ABAA82CD9664478BDA7181339B12B1C'
    sign = get_sign(data, key=key)
    data['sign'] = sign
    headers = {"Content-Type": "application/json"}
    response = requests.post(url=url, data=json.dumps(data), headers=headers)
    return response.json()


def get_sign_contract_url(shop_id):
    url = 'https://api.gdwxyf.com/api/profitShare/getSignUrl'
    data = {
        "program_id": "202316837141378884",
        "shop_id": shop_id
    }
    key = '6715C7D4435343BA0459EAEC2334D81B'
    sign = get_sign(data, key=key)
    data['sign'] = sign
    headers = {"Content-Type": "application/json"}
    response = requests.post(url=url, data=json.dumps(data), headers=headers)
    return response.json()


def check_sign_contract_result(shop_id):
    url = 'https://api.gdwxyf.com/api/profitShare/merchantSignResult'
    data = {
        "program_id": "202316837141378884",
        "shop_id": shop_id
    }
    key = '6715C7D4435343BA0459EAEC2334D81B'
    sign = get_sign(data, key=key)
    data['sign'] = sign
    headers = {"Content-Type": "application/json"}
    response = requests.post(url=url, data=json.dumps(data), headers=headers)
    return response.json()


def submit_sign_contract(shop_id, link, store_header_copy, store_indoor_copy):
    url = 'https://api.gdwxyf.com/api/profitShare/merchantSubmitApply'
    data = {
        "program_id": "202316837141378884",
        "shop_id": shop_id,
        "proportion": "1",
        "receive_shop_id": "5bd26080ae3d556018013fb41c1b2bcc",
        "cycle": "30",
        "relation": "管理方和入驻商户",
        "scene": "需求管理方与入驻方商户商品分销业务",
        "callback_url": "https://api.sutpay.com/cpay/merchantSignResult/",
        "cover_letter_link": f'["{link}"]',
        "scene_link": f'["{store_header_copy}", "{store_indoor_copy}"]',
    }
    key = '6715C7D4435343BA0459EAEC2334D81B'
    sign = get_sign(data, key=key)
    data['sign'] = sign
    headers = {"Content-Type": "application/json"}
    response = requests.post(url=url, data=json.dumps(data), headers=headers)
    return response.json()


def mmpaymkttransfers(params):
    UFDODER_URL = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers'
    API_KEY = 'xinxiangxinxiangxinxiangxinxiang'
    sign = get_sign(params, API_KEY)  # 获取签名
    params['sign'] = sign  # 添加签名到参数字典
    # print(params)
    xml = trans_dict_to_xml(params)
    response = requests.request('post', UFDODER_URL, data=xml.encode('utf-8'),
                                headers={'Content-Type': 'text/xml'}, cert=os.path.join(os.path.dirname(os.path.abspath(__file__)), "certificate/apiclient_cert.pem"))
    data_dict = trans_xml_to_dict(response.content)
    if data_dict['result_code'] != 'SUCCESS':
        if data_dict['err_code'] == 'SYSTEMERROR':
            params1 = {
                'appid': params['mch_appid'],
                'mch_id': params['mchid'],  # 商户号
                'nonce_str': params['nonce_str'],
                'partner_trade_no': params['partner_trade_no']
            }
            data_dict1 = mmpaymkttransfers_query(params1)
            if data_dict1['result_code'] == 'SUCCESS':
                data_dict1['payment_no'] = data_dict1['detail_id']
                return data_dict1
    return data_dict


def mmpaymkttransfers_query(params):
    UFDODER_URL = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo'
    API_KEY = 'xinxiangxinxiangxinxiangxinxiang'
    sign = get_sign(params, API_KEY)  # 获取签名
    params['sign'] = sign  # 添加签名到参数字典
    # print(params)
    xml = trans_dict_to_xml(params)
    response = requests.request('post', UFDODER_URL, data=xml.encode('utf-8'), headers={'Content-Type': 'text/xml'}, cert=os.path.join(os.path.dirname(os.path.abspath(__file__)), "certificate/apiclient_cert.pem"))
    data_dict = trans_xml_to_dict(response.content)

    return data_dict


def mmpaymkttransfers_xh(params):
    UFDODER_URL = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers'
    API_KEY = 'zhengshuzhengshuzhengshuzhengshu'
    sign = get_sign(params, API_KEY)  # 获取签名
    params['sign'] = sign  # 添加签名到参数字典
    # print(params)
    xml = trans_dict_to_xml(params)
    response = requests.request('post', UFDODER_URL, data=xml.encode('utf-8'),
                                headers={'Content-Type': 'text/xml'}, cert=os.path.join(os.path.dirname(os.path.abspath(__file__)), "certificate/apiclient_cert_xh.pem"))
    data_dict = trans_xml_to_dict(response.content)
    if data_dict['result_code'] != 'SUCCESS':
        if data_dict['err_code'] == 'SYSTEMERROR':
            params1 = {
                'appid': params['mch_appid'],
                'mch_id': params['mchid'],  # 商户号
                'nonce_str': params['nonce_str'],
                'partner_trade_no': params['partner_trade_no']
            }
            data_dict1 = mmpaymkttransfers_xh_query(params1)
            if data_dict1['result_code'] == 'SUCCESS':
                data_dict1['payment_no'] = data_dict1['detail_id']
                return data_dict1
    return data_dict


def mmpaymkttransfers_xh_query(params):
    UFDODER_URL = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo'
    API_KEY = 'zhengshuzhengshuzhengshuzhengshu'
    sign = get_sign(params, API_KEY)  # 获取签名
    params['sign'] = sign  # 添加签名到参数字典
    # print(params)
    xml = trans_dict_to_xml(params)
    response = requests.request('post', UFDODER_URL, data=xml.encode('utf-8'),
                                headers={'Content-Type': 'text/xml'}, cert=os.path.join(os.path.dirname(os.path.abspath(__file__)), "certificate/apiclient_cert_xh.pem"))
    data_dict = trans_xml_to_dict(response.content)
    return data_dict


def mmpaymkttransfers_infly(params):
    UFDODER_URL = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers'
    API_KEY = 'xinxiangxinxiangxinxiangxinxiang'
    sign = get_sign(params, API_KEY)  # 获取签名
    params['sign'] = sign  # 添加签名到参数字典
    # print(params)
    xml = trans_dict_to_xml(params)
    response = requests.request('post', UFDODER_URL, data=xml.encode('utf-8'), headers={'Content-Type': 'text/xml'}, cert=os.path.join(os.path.dirname(os.path.abspath(__file__)), "certificate/apiclient_cert_infly.pem"))
    data_dict = trans_xml_to_dict(response.content)
    if data_dict['result_code'] != 'SUCCESS':
        if data_dict['err_code'] == 'SYSTEMERROR':
            params1 = {
                'appid': params['mch_appid'],
                'mch_id': params['mchid'],  # 商户号
                'nonce_str': params['nonce_str'],
                'partner_trade_no': params['partner_trade_no']
            }
            data_dict1 = mmpaymkttransfers_infly_query(params1)
            if data_dict1['result_code'] == 'SUCCESS':
                data_dict1['payment_no'] = data_dict1['detail_id']
                return data_dict1
    return data_dict


def mmpaymkttransfers_infly_query(params):
    UFDODER_URL = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo'
    API_KEY = 'xinxiangxinxiangxinxiangxinxiang'
    sign = get_sign(params, API_KEY)  # 获取签名
    params['sign'] = sign  # 添加签名到参数字典
    # print(params)
    xml = trans_dict_to_xml(params)
    response = requests.request('post', UFDODER_URL, data=xml.encode('utf-8'),
                                headers={'Content-Type': 'text/xml'}, cert=os.path.join(os.path.dirname(os.path.abspath(__file__)), "certificate/apiclient_cert_infly.pem"))
    data_dict = trans_xml_to_dict(response.content)
    return data_dict


def ryx_settle_order(body):
    url = 'https://manage.gdwxyf.com/internal/saveChannelMerchantOrders.do'
    sign = get_sign(body, key='6972B6EFA4B29192A3A22E1E300AA4DE')
    body['sign'] = sign
    response = requests.post(url=url, data=json.dumps(body))
    return response.json()


def ryx_settle_order_wx(body):
    url = 'https://manage.gdwxyf.com/internal/saveChannelMerchantOrders.do'
    sign = get_sign(body, key='4C685CEA1B7724760AFE593DE533BB5A')
    body['sign'] = sign
    response = requests.post(url=url, data=json.dumps(body))
    return response.json()


def ryx_profitsharing_order(body):
    url = 'https://api.gdwxyf.com/api/profitorder.do'
    sign = get_sign(body, key='6715C7D4435343BA0459EAEC2334D81B')
    body['sign'] = sign
    response = requests.post(url=url, json=body)
    return response.json()


def check_shop_can_subsidy(shop_id, channel):
    url = 'https://manage.gdwxyf.com/internal/checkshopcansubsidy.do'
    body = {
        "shop_id": shop_id,
        "source": "wx",
        "channel": channel
    }
    sign = get_sign(body, key='4C685CEA1B7724760AFE593DE533BB5A')
    body['sign'] = sign
    response = requests.post(url=url, data=json.dumps(body))
    return response.json()


def pkcs7_padding(data):
    if not isinstance(data, bytes):
        data = data.encode()
    padder = padding.PKCS7(algorithms.AES.block_size).padder()
    padded_data = padder.update(data) + padder.finalize()
    return padded_data


def encrypt_pkcs7_padding(text, key):
    key = key.encode('utf-8')
    mode = AES.MODE_ECB
    cryptos = AES.new(key, mode)
    text = pkcs7_padding(text.encode('utf-8'))
    cipher_text = cryptos.encrypt(text)
    return base64.b64encode(cipher_text).decode('utf-8')


def encrypt_CBC_pkcs7_padding(text, key, iv):
    key = key.encode('utf-8')
    iv = iv.encode('utf-8')
    mode = AES.MODE_CBC
    cryptos = AES.new(key, mode, iv)
    text = pkcs7_padding(text.encode('utf-8'))
    cipher_text = cryptos.encrypt(text)
    return base64.b64encode(cipher_text).decode('utf-8')


def decrypt_CBC_pkcs7_padding(text, key, iv):
    key = key.encode('utf-8')
    iv = iv.encode('utf-8')
    text = base64.b64decode(text.encode('utf8'))
    mode = AES.MODE_CBC
    cryptor = AES.new(key, mode, iv)
    plain_text = cryptor.decrypt(text)
    return bytes.decode(plain_text).rstrip('\0').rstrip("\x01").rstrip("\x02").rstrip("\x03").rstrip("\x04").rstrip("\x05").rstrip("\x06").rstrip("\x07").rstrip("\x08").rstrip("\x09").rstrip("\x0a").rstrip("\x0b").rstrip("\x0c").rstrip("\x0d").rstrip("\x0e").rstrip("\x0f").rstrip("\x10")


def get_sign_HMACSHA1(data_dict, key):
    params_list = sorted(data_dict.items(), key=lambda e: e[0], reverse=False)  # 参数字典倒排序为列表
    params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list)
    print(params_str)
    key = bytes(key, encoding='utf-8')
    params_str = bytes(params_str, encoding='utf-8')
    sha1 = hmac.new(key, params_str, digestmod=hashlib.sha1)
    sign = base64.b64encode(sha1.digest()).decode()
    return sign


def get_sign_SM3(data_dict, key):
    params_list = sorted(data_dict.items(), key=lambda e: e[0], reverse=False)  # 参数字典倒排序为列表
    params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list)
    # print(f'{key}{params_str}')
    str_b = bytes(f'{key}{params_str.replace(" ", "")}', encoding='utf-8')
    sign = sm3.sm3_hash(func.bytes_to_list(str_b))
    return sign


def quying_login():
    url = 'https://h.quying.co/api/mall/service/user/login'
    nonce = random_str()
    timestamp = int(time.time())
    data = {
        "nonce": nonce,
        "timestamp": timestamp
    }
    headers = {
        "Content-Type": "application/json"
    }
    key = 'shangyishangyishangyishangyisysy'
    params_list = sorted(data.items(), key=lambda e: e[0], reverse=False)  # 参数字典倒排序为列表
    params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list) + '&key=' + key
    sign = hmac.new(bytes(key, encoding='utf-8'), bytes(params_str, encoding='utf-8'),digestmod=hashlib.sha256).digest().hex().upper()
    data['sign'] = sign
    response = requests.post(url=url, data=json.dumps(data), headers=headers)
    wyh_session = response.cookies._cookies['h.quying.co']['/']['wyh_session'].value
    return wyh_session


def get_level_distribution(coupon_stock_id):
    page = 1
    data = []
    wyh_session = quying_login()
    while True:
        url = f'https://h.quying.co/api/mall/admin/allot/get/list?coupon_stock_id={coupon_stock_id}&page={page}&size=2000'
        headers = {"Cookie": f"wyh_session={wyh_session}"}
        response = requests.get(url=url, headers=headers)
        result = response.json()
        total_page = result['page_info']['total_page']
        data += result['data']['allots']
        if page >= total_page:
            break
        page += 1
    return data


def get_wyhactivity_data(allot_id):
    page = 1
    data = []
    wyh_session = quying_login()
    while True:
        url = f'https://h.quying.co/api/mall/admin/issue/get/list?allot_id={allot_id}&page={page}&size=1000&status='
        headers = {"Cookie": f"wyh_session={wyh_session}"}
        response = requests.get(url=url, headers=headers)
        result = response.json()
        total_page = result['page_info']['total_page']
        data += result['data']['issues']
        if page >= total_page:
            break
        page += 1
    return data


def get_wyhactivity_status(stock_id):
    wyh_session = quying_login()
    url = f'https://h.quying.co/api/mall/admin/statistic/search?stock_id={stock_id}'
    headers = {"Cookie": f"wyh_session={wyh_session}"}
    response = requests.get(url=url, headers=headers)
    result = response.json()
    total_page = result['page_info']['total_page']
    if total_page == 0:
        return ''
    return result['data']['activities'][0]['status']


def update_wyhactivity_data_level(allot_id_list, marketer_tel):
    wyh_session = quying_login()
    for allot_id in allot_id_list:
        url = f'https://h.quying.co/api/mall/admin/issue/get/list?allot_id={allot_id}&page=1&size=10&keyword={marketer_tel}'
        headers = {"Cookie": f"wyh_session={wyh_session}"}
        response = requests.get(url=url, headers=headers)
        result = response.json()
        total = result['page_info']['total']
        if total != 0:
            return allot_id
    return ''


def get_wyhactivity_csvdata(register_id_list, activity_id_list):
    rewardList = []
    data = []
    wyh_session = quying_login()
    headers = {"Cookie": f"wyh_session={wyh_session}"}
    for activity_id in activity_id_list:
        page = 1
        while True:
            url = f'https://h.quying.co/api/mall/admin/public/get/rewardList?tel=&activity_id={activity_id}&page={page}&size=1000&status=NORMAL'
            response = requests.get(url=url, headers=headers)
            result = response.json()
            total_page = result['page_info']['total_page']
            rewardList += result['data']['registers']
            if page >= total_page:
                break
            page += 1
    for reward in rewardList:
        if reward['register_id'] not in register_id_list:
            url = f'https://h.quying.co/api/mall/admin/public/get/rewardDetails?register_id={reward["register_id"]}&page=1&size=10&status='
            response = requests.get(url=url, headers=headers)
            result = response.json()
            data += result['data']['list']
    return data


def get_wyhactivity_relevance():
    page = 1
    data = []
    wyh_session = quying_login()
    while True:
        url = f'https://h.quying.co/api/mall/admin/get/activity/list?public_activity_type=&public_activity_title=&activity_id=&list_province=&list_city=&list_district=&list_net=&type=PUBLIC&page={page}&size=1000&status='
        headers = {"Cookie": f"wyh_session={wyh_session}"}
        response = requests.get(url=url, headers=headers)
        result = response.json()
        total_page = result['page_info']['total_page']
        data += result['data']['activities']
        if page >= total_page:
            break
        page += 1
    return data


def get_ylx_level_distribution_list(actId, orgId, data):
    token = Channel.objects.get(id=5).cookie
    method = 'GiftBagCouponGetAllotList'
    body = {"actId":actId,"orgId":orgId}
    result = json.loads(get_result(method, body, token))
    allotList = result['data']['allotList']
    data += allotList
    for allot in allotList:
        if allot['hasChild']:
            get_ylx_level_distribution_list(allot['actId'], allot['orgId'], data)
    return data


def get_ylx_level_distribution(coupon_stock_id):
    token = Channel.objects.get(id=5).cookie
    method = 'GiftBagCouponGetActivityList'
    body = {"page":"1","pageSize":"10","stockId":coupon_stock_id}
    result = json.loads(get_result(method, body, token))
    total = result['data']['pageInfo']['total']
    if total == '0':
        return []
    actId = result['data']['activityList'][0]['id']
    data = get_ylx_level_distribution_list(actId, '', [])
    return data


def get_ylxactivity_data(coupon_stock_id):
    token = Channel.objects.get(id=5).cookie
    method = 'GiftBagCouponGetActivityList'
    body = {"page":"1","pageSize":"10","stockId":coupon_stock_id}
    result = json.loads(get_result(method, body, token))
    total = result['data']['pageInfo']['total']
    if total == '0':
        return []
    actId = result['data']['activityList'][0]['id']
    method = 'ExportSubmit'
    body = {"type":"GIFTBAGCOUPON_RECEIVE_RECORD","searchData":"{\"marketerMobile\":\"\",\"marketerName\":\"\",\"mobile\":\"\",\"openId\":\"\",\"orgId\":\"\",\"status\":\"normal\"}","additionalData":"{\"actId\":" + actId + "}"}
    result = json.loads(post_result(method, body, token))
    export_id = result['data']['export']['id']
    a = 0
    while True:
        method = 'ExportList'
        body = {"page":"1","status":"ENDED", "type": "GIFTBAGCOUPON_RECEIVE_RECORD"}
        result = json.loads(get_result(method, body, token))
        total = result['data']['pageInfo']['total']
        exportList = result['data']['exportList']
        if total == '0':
            return []
        for i in exportList:
            if i['id'] == export_id:
                url = i['file']['url']
                response = requests.get(url=url)
                content = response.content.decode()
                content = content.split('\n')[1:-1]
                return content
        time.sleep(10)
        if a == 100:
            return []
        a += 1

    # return data


def get_ylxactivity_data_status(mobile, stockNo):
    token = Channel.objects.get(id=5).cookie
    method = 'AllCouponLogList'
    body = {"page":"1","pageSize":"10","mobile":mobile,"stockNo":stockNo}
    result = json.loads(get_result(method, body, token))
    return result['data']['list'][0]['status']


def get_ylxactivity_publicity_data(stockNo):
    # token = Channel.objects.get(id=5).cookie
    # method = 'AllCouponLogList'
    # page = 1
    # data = []
    # while True:
    #     body = {"page": str(page), "pageSize": "100", "stockNo": stockNo}
    #     result = json.loads(get_result(method, body, token))
    #     total_page = result['data']['pageInfo']['totalPage']
    #     data += result['data']['list']
    #     if page >= int(total_page):
    #         break
    #     page += 1
    # return data
    token = Channel.objects.get(id=5).cookie
    method = 'GiftBagCouponGetActivityList'
    # body = {"page":"1","pageSize":"10","stockId":coupon_stock_id}
    # result = json.loads(get_result(method, body, token))
    # total = result['data']['pageInfo']['total']
    # if total == '0':
    #     return []
    # actId = result['data']['activityList'][0]['id']
    method = 'ExportSubmit'
    body = {"type":"VMALL-ACTIVITY-COUPON-EXPORT","searchData":"{\"status\":\"\",\"couponId\":\"\",\"equityName\":\"\",\"mobile\":\"\",\"stockNo\":\"" + stockNo + "\"}","additionalData":"{\"staffId\":\"267350237377711480\",\"orgId\":\"0\",\"isSuper\":true,\"channelId\":\"imqdOwwzbPNJqSdkUUW3\",\"isBackClient\":true,\"actId\":\"\"}"}
    result = json.loads(post_result(method, body, token))
    export_id = result['data']['export']['id']
    a = 0
    while True:
        method = 'ExportList'
        body = {"page":"1","status":"ENDED", "type": "GIFTBAGCOUPON_RECEIVE_RECORD"}
        result = json.loads(get_result(method, body, token))
        total = result['data']['pageInfo']['total']
        exportList = result['data']['exportList']
        if total == '0':
            return []
        for i in exportList:
            if i['id'] == export_id:
                url = i['file']['url']
                response = requests.get(url=url)
                content = response.content.decode()
                content = content.split('\n')[1:-1]
                return content
        time.sleep(10)
        if a == 100:
            return []
        a += 1


if __name__ == '__main__':
    # print(get_wyhactivity_csvdata([], [4446,4447]))
    # print(get_ylxactivity_publicity_data('17342891'))

    # params = {
    #     'appid': 'wxf68630951d36fd07',
    #     'mch_id': '1486198522',  # 商户号
    #     'nonce_str': '2OvVvJ2NWRhbZV3bm8njYOG4siXDg39E',
    #     'partner_trade_no': '2024061108342556531300000'
    # }
    # data_dict = mmpaymkttransfers_query(params)
    # print(data_dict)
    from merchants.models import Merchant, MerchantImage, MerchantMallApplyment

    merchant = Merchant.objects.get(wyfMerchantID=6021399761)
    store_indoor_copy = MerchantImage.objects.filter(merchant_id=merchant.id).first()
    mall_applyment = MerchantMallApplyment.objects.filter(merchant_id=merchant.id, applyment_type=1).last()
    if not store_indoor_copy:
        store_indoor_copy = merchant.store_header_copy.url
    else:
        store_indoor_copy = store_indoor_copy.image.url
    result = submit_sign_contract(merchant.ruiyinxinMerchantID, mall_applyment.contract.url, merchant.store_header_copy.url, store_indoor_copy)
    print(result)